/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.downlove.common.RequestContext;
import com.downlove.common.StorageService;
import com.downlove.common.Storage.ImageInfo;
import com.downlove.database.QueryHelper;
import com.zito.ErrMsgException;
import com.zito.bean.Video;
import com.zito.common.Paginator;

/**
 * @author yjx
 * 
 */
public class VideoManager {

	private Paginator paginator;
	private final Logger logger = LoggerFactory.getLogger(VideoManager.class);
	int imageSize = 3000 * 1024;

	/**
	 * 分页
	 * 
	 * @return
	 */
	public String getPaginator() {
		return this.paginator.getCssPageBlock();
	}

	public Paginator getPaginatorBean() {
		return this.paginator;
	}

	/**
	 * 图片上传
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public ImageInfo uploadImages() throws ErrMsgException,
			IOException {
		RequestContext rc = RequestContext.get();
		Enumeration<String> files = rc.getFileNames();
		ImageInfo info = null;
		while (files.hasMoreElements()) {
			String filename = files.nextElement();
			File imgFile = rc.image(filename);
			if (imgFile.length() > imageSize) {
				throw new ErrMsgException("您上传的- " + imgFile.getName()
						+ " -图片过大，系统仅允许上传：" + imageSize / 1024 + "K 大小的文件");
			}
			info = StorageService.IMAGES.saveImage(imgFile).Thumbnail().getImageInfo();
		}
		return info;
	}
	
	/**
	 * 加载视频列表
	 * 
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Video> getVideoListAll(int pagesize) {
		RequestContext rc = RequestContext.get();
		Video obj = new Video();
		int total = obj.TotalCount();
		String filter = " 1 = 1 ";
		this.paginator = new Paginator(rc, total, pagesize);
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = obj.idListFilter(filter, curpage, pagesize);
		return obj.LoadList(tmpList);
	}

	/**
	 * 加载视频列表
	 * 
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Video> getVideoList(int pagesize) {
		RequestContext rc = RequestContext.get();
		Video obj = new Video();
		String filter = " isshow = 1 ";
		int total = obj.TotalCount(filter);
		this.paginator = new Paginator(rc, total, pagesize);
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = obj.idListFilter(filter, curpage, pagesize);
		return obj.LoadList(tmpList);
	}
	
	/**
	 * 查询上一篇
	 * @param columnid
	 * @param articleid
	 * @param postdate
	 * @return
	 * @throws Exception
	 */
	public Video getLastVideo(Long videoid,String postdate) throws Exception{
		String sql ="SELECT * FROM Video WHERE postdate>=? AND ID != ? AND isshow = 1 ORDER BY topic DESC,postdate Limit 1";
		Video obj = new Video();
		obj = QueryHelper.read(Video.class, sql, postdate,videoid);
		return obj;
	}
	

	/**
	 * 查询下一篇 
	 * @param columnid
	 * @param articleid
	 * @param postdate
	 * @return
	 * @throws Exception
	 */
	public Video getNextVideo(Long videoid,String postdate) throws Exception{
		String sql ="SELECT * FROM Video WHERE postdate<=? AND ID != ? AND isshow = 1 ORDER BY topic DESC,postdate DESC Limit 1";
		Video obj = new Video();
		obj = QueryHelper.read(Video.class, sql, postdate,videoid);
		return obj;
	}
	
	/**
	 * 根据ID 获取实体类
	 * 
	 * @return
	 */
	public Video getVideo() {
		RequestContext rc = RequestContext.get();
		Video obj = new Video();
		long id = rc.param("id", -1);
		if (id == -1)
			return null;
		return obj.Get(id);
	}
	
	/**
	 * 更新点击次数
	 * @return
	 */
	public boolean UpdateView(Long videoid) throws Exception{
		boolean re = false;
		String sql ="UPDATE video SET clicknum = clicknum+1 WHERE ID = ?";
		re = QueryHelper.update(sql, videoid)>0;
		return re;
	}

	/**
	 * 保存
	 * 
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean operatingPost() throws Exception {
		RequestContext rc = RequestContext.get();
		Video obj = new Video();
		long tempid = rc.param("id", -1);
		obj = obj.Get(tempid);
		return obj == null ? insertData(rc) : editData(rc);
	}

	/**
	 * 新增
	 * 
	 * @param rc
	 * @return
	 * @throws Exception
	 */
	public boolean insertData(RequestContext rc) throws Exception {
		Video obj = new Video();
		obj = rc.form(Video.class);
		String error = obj.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		obj.setClicknum(0);
		obj.setTopic(0);
		obj.setOrders(0);
		obj.setAuthorid(MasterSession.get().getUserID());
		obj.setAuthor(MasterSession.get().getUserName());
		return obj.Save() != -1L;
	}

	/**
	 * 编辑
	 * 
	 * @param rc
	 * @return
	 * @throws Exception
	 */
	public boolean editData(RequestContext rc) throws Exception {
		Video obj = new Video();
		obj = rc.form(Video.class);
		String error = obj.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		return obj.Update() != -1L;
	}

	/**
	 * 删除
	 * 
	 * @return
	 * @throws ErrMsgException
	 */
	public boolean deleteData() throws Exception {
		RequestContext rc = RequestContext.get();
		Video obj = new Video();
		obj = rc.form(Video.class);
		if (obj.getId() == -1)
			return false;
		String deleteSql = "DELETE FROM Video WHERE id=?";
		boolean flag = true;
		try {
			QueryHelper.update(deleteSql, obj.getId());
		} catch (Exception e) {
			flag = false;
			logger.error("删除视频时出现异常：{}", e.getMessage());
			throw new ErrMsgException("删除视频时出现异常:" + e.getMessage());
		}
		// 数据删除成功后删除硬盘上文件,无论文件是否存在，在删除时不返回任何异常
		if (flag && obj.getSerpath().length() > 0) {
			FileUtils.deleteQuietly(new File(RequestContext.root()
					+ obj.getSerpath()));
		}
		return true;
	}
}
